package com.example.demo.service.impl;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author gyc
 * @date 2018/1/7
 */
@Service
public class UserServiceImpl implements UserService {
    private final static Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserDao userDao;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User findById(Integer id) {
        // 从缓存中获取城市信息
        String key="user_"+id;
        ValueOperations<String,User> operations=redisTemplate.opsForValue();

        boolean haskey=redisTemplate.hasKey(key);
        if(haskey){
            User user=operations.get(key);
            logger.info("UserServiceImpl.findById()从缓存中获取用户："+user.toString());
            return user;
        }
        // 从 DB 中获取城市信息
        User user=userDao.findById(id);
        // 插入缓存
        operations.set(key,user,10, TimeUnit.SECONDS);
        logger.info("UserServiceImpl.findById()将用户插入缓存："+user.toString());
        return user;

    }

    @Override
    public Integer saveUser(User user) {
        return userDao.saveUser(user);
    }

    @Override
    public Integer updateUser(User user) {
        Integer num=userDao.updateUser(user);

        String key="user_"+user.getId();
        boolean haskey=redisTemplate.hasKey(key);
        if(haskey){
            redisTemplate.delete(key);
            logger.info("updateUser删除缓存中的用户信息"+user.toString());
        }
        return num;
    }

    @Override
    public Integer deleteUser(Integer id) {
        Integer num=userDao.deleteUser(id);

        String key="user_"+id;
        boolean haskey=redisTemplate.hasKey(key);
        if(haskey){
            redisTemplate.delete(key);
            logger.info("根据ID删除缓存的用户信息:"+id);
        }
        return num;
    }
}
